import { TIME_INTERVAL } from '@/assets/constant/other-constants';
import dayjs from 'dayjs';
import { ComponentWithComputed } from 'miniprogram-computed';

ComponentWithComputed({
  properties: {
    /** 启始时间 */
    startDate: {
      type: String,
      value: dayjs().format('YYYY-MM-DD'),
    },
    // XXX 结束时间 暂时定死到10年后，后续再添加具体参数和相关逻辑
    /** 可选择的时间段 */
    timeInterval: {
      type: Array,
      value: [],
    },
    /** 文字颜色 */
    color: {
      type: String,
      value: '#ff457a',
    },
  },
  data: {
    value: [0, 0, 0, 0],
  },
  computed: {
    years(data: { startDate: string }) {
      const LENGTH = 10;
      return Array.from({ length: LENGTH }, (_, k) => dayjs(data.startDate).year() + k);
    },
    months(data) {
      // @ts-ignore 实际上是可以通过data访问其他计算属性的，可能是因为miniprogram-computed的类型提示没考虑到
      const { startDate, value, years } = data;
      const year = years[value[0]];
      return year === dayjs(startDate).year()
        ? Array.from({ length: 12 - dayjs().month() }, (_, k) => dayjs().month() + k + 1)
        : Array.from({ length: 12 }, (_, k) => k + 1);
    },
    days(data) {
      // @ts-ignore 实际上是可以通过data访问其他计算属性的，可能是因为miniprogram-computed的类型提示没考虑到
      const { startDate, value, years, months } = data;
      const year = years[value[0]];
      const month = months[value[1] > months.length - 1 ? months.length - 1 : value[1]];
      const daysInMonth = dayjs(`${year}-${month}`).daysInMonth();
      return month === dayjs(startDate).month() + 1
        ? Array.from({ length: daysInMonth - dayjs(startDate).date() + 1 }, (_, k) => dayjs().date() + k)
        : Array.from({ length: daysInMonth }, (_, k) => k + 1);
    },
  },
  methods: {
    async onPickerViewChange(e: WechatMiniprogram.PickerViewChange) {
      const { value } = e.detail;

      this.setData({
        value,
      });

      await new Promise((resolve) => {
        wx.nextTick(resolve);
      });

      // XXX 检查value，尽量让新的日期和旧的日期接近

      const newDate = dayjs(`${this.data.years[value[0]]}-${this.data.months[value[1]]}-${this.data.days[value[2]]}`);
      this.triggerEvent('change', {
        date: newDate.format('YYYY-MM-DD'),
        time_interval: TIME_INTERVAL[value[3]],
      });
    },
  },
});
